import Vue from 'vue'
import VueRouter from 'vue-router'

// 重写官方的push方法
const originPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(location, resolve, reject) {
  if (resolve || reject) {
    return originPush.call(this, location, resolve, reject)
  }
  return originPush.call(this, location).catch(e => e);
}

Vue.use(VueRouter)

const routes = [{
  path: '/login',
  name: 'login',
  component: () => import('@/views/login')
}]

// 不需要登录就能访问的页面
const annoUrls = ['/login'];

// 是否添加过路由
let addRouterFlag = false;

let user = null;

// 要添加的路由
let addRouters = [{
  path: '/',
  component: () => import('@/views/layout'),
  children: []
}, {
  path: '*',
  component: () => import('@/views/404')
}]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  let index = annoUrls.findIndex(item => item == to.path);
  if (index != -1) {
    next();
    return;
  }
  if (!user) {
    try {
      user = JSON.parse(sessionStorage.getItem('user'));
    } catch(e) {
      // 用户没有登录
      next('/login');
      return;
    }
    if (!user) {
      next('/login');
      return;
    }
    if (!addRouterFlag) {
      createRouter(user.routers);
      addRouters[0].children = user.routers;
      addRouters[0].redirect = user.routers[0].path;
      router.addRoutes(addRouters);
      next({...to, replace: true});
      return;
    }
  }
  next();
});

// 创建路由
function createRouter(routers) {
  routers.forEach(item => {
    let name = item.component;
    item.component = () => import(`@/views/layout/${name}`);
    if (item.children && item.children.length) {
      createRouter(item.children);
    }
  })
}

export default router
